<?php
/**
 * @version $Id: controller.php 422 2012-03-19 06:52:46Z lnmtrung $
 */
 
//no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');
jimport('joomla.user.helper');

class WrdController extends JControllerLegacy {

	public function display($cache = true) {
		$document = & JFactory::getDocument();
		$url = JURI::root().'administrator/components/com_wrd/assets/js/jquery-1.4.2.min.js';
		$document->addScript($url);
		
		if (!JRequest::getVar('view'))
			JRequest::setVar('view', 'dashboard');
		parent::display($cache);
		
	}
	
	public function checkEmailOverlap(){
		
		$q = &JRequest::getVar('q');
		$userid = &JRequest::getVar('userid');
		$db = &JFactory::getDbo();
		
		$query=" SELECT email FROM #__users where email like '%$q%' AND id != ".$userid;
        $db->setQuery( $query );
        $tagList =  $db->loadObjectList();
	
		if(is_array($tagList)){
			
			foreach($tagList as $t)
			{
				echo "{$t->email}\n";
			}
		}

		jexit();
	}
	
	public static function convertPointToSummary(){
		$db = JFactory::getDbo();
		$query = 'SELECT g.user_id,p.member_id FROM #__user_usergroup_map g 
			      LEFT JOIN #__wrd_profile as p ON `g`.user_id = `p`.user_id WHERE group_id = 2';
		
		$db->setQuery($query);
		$rows = $db->loadObjectList();

		$obj = new stdClass;
		foreach($rows as $row):
			$point = WrdHelper::getPoints($row->user_id);
			$obj->member_id =  $row->member_id;
			$obj->point = $point;
			$obj->year = date('Y');
			$obj->month = date('m') - 1;
			$db ->insertObject('#__wrd_points_summary', $obj); 
		endforeach;
	
	}
	
	function h(){
		ini_set('max_execution_time', 86400);
		$sql = 'SELECT DISTINCT a.vip_number,transaction_id FROM #__wrd_transaction AS a GROUP BY vip_number';
		$db = JFactory::getDbo();
		$db->setQuery($sql);
		$rows = $db->loadObjectList();
		$i = 0;
		foreach($rows as $row):
			if(!empty($row->vip_number)):
				$q = "SELECT DISTINCT user_id FROM #__wrd_profile WHERE member_id=".$row->vip_number;
				$db->setQuery($q);
				$rss = $db->loadObjectList();
				foreach($rss as $rs){
					$query = 'SELECT SUM(point) as total FROM #__wrd_point WHERE user_id = '.$rs->user_id;
					$db->setQuery($query);
					$total = $db->loadObject();
					if($total->total == 0) {echo "Transacion_id: ".$row->transaction_id ." User_id: ".$rs->user_id." &nbsp;, Member_id: ".$row->vip_number."<br/>";$i++;}
				}
			endif;	
		endforeach;
		echo "Tong so Member co transaction nhung co diem bang khong la :".$i;
	}
	
	public function test(){
		
		$db = JFactory::getDbo();
		$query = 'SELECT user_id FROM #__wrd_profile';
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$count = 0;
		foreach($rows as $row):
			
			if($row->user_id != ''): 
			
				$sql = 'SELECT point,user_id FROM #__wrd_points_summary WHERE user_id = '. $row->user_id .' ORDER BY year DESC,month DESC LIMIT 1';
				$db->setQuery($sql);
				
				$rs = $db->loadObject();
				$query = 'UPDATE #__wrd_profile SET p_o_u = '.$rs->point.' ,point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$rs->user_id;
				$db->setQuery($query);
				$db->query();
				
			endif;
		
		endforeach;
		echo "Successfull";
	}
	
	//Convert total of #__wrd_transaction in to total_spend of #__wrd_profile
	public function convertSpend(){
		$sql = 'SELECT vip_number,sum(total) as total FROM #__wrd_transaction GROUP BY vip_number';
		$db = JFactory::getDbo();
		$db->setQuery($sql);
		$rows = $db->loadObjectList();
		foreach($rows as $row):
			if($row->vip_number != ''){
				$q = "UPDATE #__wrd_profile SET `total_spend`= '".$row->total."' WHERE member_id=".$row->vip_number;
				$db->setQuery($q);
				$db->query();
				echo $q.'<br/>';
			}
		endforeach;
		echo 'Thank you for update total_spend of #__wrd_profile';
	}
	
	public function covertSpendToSpendSummary(){
		ini_set('max_execution_time', 86400);
		$sql = 'SELECT vip_number,date_receipt FROM #__wrd_transaction WHERE pax="0" and food="0" and beverage="0" and other="0" and total=netsale';
		$db = JFactory::getDbo();
		$db->setQuery($sql);
		$rows = $db->loadObjectList();
		foreach($rows as $row):

			if(($row->vip_number != '')&&($row->date_receipt !='')){
				
				$year = date('Y',strtotime($row->date_receipt));
				$month = date('m',strtotime($row->date_receipt));

				if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
					while(($month != date('m'))||($year != date('Y'))){
						WrdHelper::uSummarySpend($row->vip_number,$year,$month);
						if($month+1 <=12) ++$month;
						else {$month = 1;++$year;}
					}
				}
				WrdHelper::uSummarySpend($row->vip_number,date('Y'),date('m'));
				
				$totalS = WrdHelper::getTotalTransaction($row->vip_number);
				$q = "UPDATE #__wrd_profile SET `total_spend`= '".$totalS->total ."' WHERE member_id=".$row->vip_number;
				$db->setQuery($q);
				$db->query();
				
			}
		endforeach;
		echo 'Update successful';
		
	}
	
	public function checkTransaction(){
		$transaction_id = $_POST['transaction_id'];
		$sql = 'SELECT count(*) as total FROM #__wrd_transaction WHERE transaction_id ='.$transaction_id;
		$db = JFactory::getDbo();
		$db->setQuery($sql);
		$rs = $db->loadObject();
		echo $rs->total;
		exit();
	}
	public function renewCode(){
		//
		$userID = JRequest::getVar('userid');
		$id = JRequest::getVar('id');
		if ($userID){
			$member_id = $this->getUserInfo($userID);
			if($member_id){
				$memberIDNew = $this->renewMemberId();
				$this->updateNewCodeUser($userID, $memberIDNew, $member_id);
			}
		}
		$this->setMessage(JText::_('Renew success!')); 
		$this->setRedirect(JRoute::_('index.php?option=com_wrd&controller=profile&id='.$id.'&layout=form', false));
	}
	
	protected function getUserInfo($userID=null){
		if(isset($userID) && $userID != ''){
			$db = JFactory::getDbo();
			$query = "SELECT member_id FROM #__wrd_profile WHERE sha1(user_id)='".$userID. "' LIMIT 1";
			$db->setQuery($query);
			$rs = $db->loadObject();
			if($rs->member_id){
				return $rs->member_id;
			}
			return false;
		}
	}
	
	function updateNewCodeUser($userID=null, $memberIDNew=null, $memberIDOld=null){
		$db = JFactory::getDbo();
		
		//Update new member ID for Profile
		$sqlQuery = sprintf("UPDATE #__wrd_profile SET member_id=$memberIDNew, renew='A' WHERE sha1(user_id)=%s", $db->Quote($userID));
		$updateNewMemberID = $db->setQuery($sqlQuery);
		$updateNewMemberID->query();
		
		//Update new vip_number as member_id for transaction
		$sqlQuery = sprintf("UPDATE #__wrd_transaction SET vip_number=$memberIDNew WHERE vip_number=%s", $db->Quote($memberIDOld));
		$updateNewMemberID = $db->setQuery($sqlQuery);
		$updateNewMemberID->query();
	}
	
	public static function renewMemberId(){
		return WrdHelper::uRenewMemberId();
	}
	
	//Giong ham renewMemberId nhung khac kieu tra ve
	public static function renewMember(){
		
		$db = &JFactory::getDBO();
		$query_lucky = 'SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1';
		$db->setQuery($query_lucky);
		$rs_lucky = $db->loadResultArray();

		$query = 'SELECT member_id FROM #__wrd_profile';
		$query.= ' WHERE member_id NOT IN (SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1)';		
		$query.= ' ORDER BY member_id DESC LIMIT 1';
		$db->setQuery($query);
		$rs = $db->loadObject();
		$code = $rs->member_id + 1;
		
		$tmparr = $rs_lucky;
		$total = count($tmparr)*2 ;
		
		for($i = 0 ; $i <= $total ; $i++){
			$tmparr[] = $code + $i ;
		}
		
		$tmparr = array_unique($tmparr,SORT_NUMERIC) ;
		sort($tmparr) ;
		foreach ($tmparr as $val){
			if(in_array($val, $rs_lucky)){
				continue;
			}else{
				$code = $val;
				break;
			}
		}
		
		echo $code;
		jexit();
		
	}

	public function generateMemberId(){
		
		$db = JFactory::getDBO();
		$query_lucky = 'SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1';
		$db->setQuery($query_lucky);
		$rs_lucky = $db->loadResultArray();
		$query = 'SELECT member_id FROM #__wrd_profile ' ;
		$query.= ' WHERE member_id NOT IN (SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1)';		
		$query.= ' ORDER BY member_id DESC LIMIT 1';
		$db->setQuery($query);
		$rs = $db->loadObject();
		$code = $rs->member_id + 1;
		
		$tmparr = $rs_lucky;
		$total = count($tmparr)*2 ;
		
		for($i = 0 ; $i <= $total ; $i++){
			$tmparr[] = $code + $i ;
		}
		
		$tmparr = array_unique($tmparr,SORT_NUMERIC) ;
		sort($tmparr) ;
		
		foreach ($tmparr as $val){
			if(in_array($val, $rs_lucky)){
				continue;
			}else{
				$code = $val;
				break;
			}
		}
		
		echo $code ;
		jexit();
	}
	
	function updateUser(){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__masterlist';
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		$obj = new stdClass();
		foreach ($rs as $val=>$item){
			$query = 'SELECT * FROM #__wrd_profile WHERE member_id ='.str_ireplace('V', '', $item->member_no);
			$db->setQuery($query);
			$profile_obj = $db->loadObject();
			
			if($profile_obj != null){
				$fln = explode(' ', $item->member_mailing);
				$sumfln = count($fln);
				
				$obj = new stdClass();
				$obj->id = $profile_obj->id;
				$obj->f_name = $fln[$sumfln-1];
				$obj->l_name = trim(str_ireplace($fln[$sumfln-1], '', $item->member_mailing));
				$db->updateObject('#__wrd_profile', $obj,'id');	
			}
			echo 'Update user id '.$obj->id.', '.$sumfln.'<br />';
		}
	}
	
	public function changetopickup(){
		$id = JRequest::getVar('id');
		$date = JRequest::getVar('date');
		if($id == 0)
			return false;
		
		$db = JFactory::getDBO();
		$query = 'UPDATE #__wrd_profile SET `pick_up_date` ="'.$date.'" WHERE id = '.$id;
		$db->setQuery($query);
		$db->query();
		jexit();
		return true;
	}
	
    public function importUserExcel(){
        $db = JFactory::getDbo();
        $query = 'SELECT * FROM #__masterlist';
        $db->setQuery($query);
        $rs = $db->loadObjectList();
        $obj = new stdClass();
        
    }
    
	public function importUser(){
	
		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', 86400);
		$db = JFactory::getDbo();        
		
		$query = 'SELECT * FROM #__masterlist WHERE `status` = 1 OR `status` = 0';
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		
		$district = WrdHelper::getDistrict();
        $city = WrdHelper::getCity();
        
        $obj = new stdClass();
        $count = 1;
		foreach ($rs as $val=>$item){

			$date = date("Y-m-d H:i:s");
            
			$obj->id = null;
			
			//Modify by JWan - 2012/10/11
			if(($item->email == '')||($item->email == '0')||(!isset($item->email))){
				$email = str_ireplace('V', '', $item->member_no).'@wmcvip.vn';
			}
			else {
				$email = $item->email;
			}
			
            $member_noTemp = str_ireplace('V', '', $item->member_no);
			
            $arrdob = explode('-', $item->date_of_birth);
            $pass =  md5($member_noTemp.$arrdob[0]);
            
	            	if($item->status == 1){
	                    $obj->name = $member_noTemp;
	                    $obj->username = $member_noTemp;
	                    
	                    $obj->email = $email;
						$obj->password = $pass; //update pass below
	                    $obj->usertype ='';
	                    $obj->block = '0';
	                    $obj->sendEmail = 0;
	                   
	                    /*********** Date ***********/
	                    if($item->member_joining_date != '')
	                    {
	                        $obj->registerDate = $item->member_joining_date;    
	                    }
	                    else
	                    {
	                        $obj->registerDate = '';
	                    }
	                    
	                    $obj->lastvisitDate ='0000-00-00 00:00:00';
	                    $obj->activation = '';
	                    $obj->params = '{}';
	                    $db->insertObject('#__users', $obj);
	                    $insert_id = $db->insertid(); 
	                    //$insert_id = 0;
	           
	                
	                    $group_obj = new stdClass();
	                    $group_obj->user_id = $insert_id;
	                    $group_obj->group_id = 2;
						$db->insertObject('#__user_usergroup_map', $group_obj);     
	             	}
	             	
                    //caculate fname lname            
                    $fln = explode(' ', $item->member_mailing);
                    $sumfln = count($fln);
                    
                    //caculate DOB            
                    $profile_obj = new stdClass();
                    $profile_obj->id = null;
                    $profile_obj->prefix  = trim(str_ireplace('.', '', $item->title)).'.';
                    $profile_obj->user_id = $insert_id;
                    $profile_obj->f_name = $fln[$sumfln-1];
                    $profile_obj->l_name = trim(str_ireplace($fln[$sumfln-1], '', $item->member_mailing));
                    
                    $profile_obj->published = 1;
                    
                    /*********** Date ***********/
                    if($item->member_joining_date != '')
                    {
                        $profile_obj->created_date = $item->member_joining_date;   
                    }
                    else
                    {
                        $profile_obj->created_date = '';
                    }
                    
                    /*********** Date ***********/
                    if($item->date_of_birth != '')
                    {
                        $profile_obj->dob = $item->date_of_birth;
                    }
                    else
                    {
                        $profile_obj->dob = '';
                    }
                    
                    
                    $profile_obj->member_id = str_ireplace('V', '', $item->member_no);
                    
                    $profile_obj->job = null;
                    
                    /******** Company Information ********/                    
                    $profile_obj->c_info = null;
                    $profile_obj->c_distric = WrdHelper::getIdDistrictValueByName($district, $item->organisation_postal_address_3);
                    
                    if($profile_obj->c_distric == '')
                    {
                        $profile_obj->c_distric = WrdHelper::getIdDistrictValueByName($district, $item->organisation_postal_address_2);    
                    }
                    
                    if($profile_obj->c_distric == '')
                    {
                        $profile_obj->c_addr = trim($item->organisation_postal_address_1, ',');
                        $profile_obj->c_addr .= ', '.trim($item->organisation_postal_address_2, ',');
                        $profile_obj->c_addr .= ', '.trim($item->organisation_postal_address_3, ',');
                    }
                    else
                    {
                        $profile_obj->c_addr = trim($item->organisation_postal_address_1, ',');
                        $profile_obj->c_addr .= ', '.trim($item->organisation_postal_address_2, ',');
                    }
                    if($item->title == 'Dr' || $item->title == 'Mr' || $item->title == 'Mr.')
                    {
                        $profile_obj->gender= 'male';    
                    }
                    else
                    {
                        $profile_obj->gender= 'female';
                    }
                    
                    $profile_obj->industry 		= null;
                    $profile_obj->department 	= null;
                    $profile_obj->education 	= null;
                    $profile_obj->o_club 		= null;
                    $profile_obj->income 		= null;
                    $profile_obj->hobbies 		= null;
                    $profile_obj->phone 		= $item->mobile_no;
                    
                   
                    /******** Basic Information ********/             
                    $profile_obj->distric = WrdHelper::getIdDistrictValueByName($district, $item->member_residential_address_line_3);
                    
                    if($profile_obj->distric == 0){
                    	$profile_obj->city = WrdHelper::getCityValueByName($city, $item->member_residential_city);
                    	if(intval($profile_obj->city) <= 0)
                    		$profile_obj->country = 0;
                    	else
                    		$profile_obj->country = WrdHelper::getCountryCodeFromCity($profile_obj->city);
                    }
                    else
                    {
                    	$profile_obj->city = WrdHelper::getCityCodeFromDistric($profile_obj->distric);
                    	$profile_obj->country = WrdHelper::getCountryCodeFromDistric($profile_obj->distric);
                    }
                    
                    $profile_obj->address = trim($item->member_residential_address_line_1, ',');
                    $profile_obj->address .= ', '.trim($item->member_residential_address_line_2, ',');

                    /******** Job ********/
                    $ocupation = WrdHelper::getJobTitleOcupation($item->occupation);
                    $profile_obj->job = $ocupation[1];
                    $profile_obj->o_job = $ocupation[2];
                    $profile_obj->job_prefix = $ocupation[0];
                    $profile_obj->nationality = WrdHelper::importNationality($item->nationality);
                    $profile_obj->step = null;
                    $profile_obj->created_id = 42;
                    $profile_obj->modify_date = $date;
                    $profile_obj->website = null;
                    $profile_obj->skype = null;
                    $profile_obj->yahoo = null; 
                    $profile_obj->gtalk = null;
                    $profile_obj->social = null;
                    $profile_obj->msn = null;
                    $profile_obj->c_country = null;
                    $profile_obj->c_city = null;
                    $profile_obj->referer = null;
                    $profile_obj->referer_phone = $item->home_no;
                    $profile_obj->status = null;
                    $profile_obj->country_code = null;
                    $profile_obj->p_email = $email;
                    $profile_obj->name_on_card = null;
                    $profile_obj->company_name = $item->organisation_name;
                    $profile_obj->status_of_card = 1;
					
					if(substr($item->receiving_slip,0,4) > 1980){
						$profile_obj->status_of_card = 3;
					}
					else if(substr($item->delivered_vipcard_date,0,4) > 1980){
						$profile_obj->status_of_card = 2;
					}
						
                    $profile_obj->status_of_card_date = $item->masterlist_created;
                    
                    $profile_obj->pick_up_at = WrdHelper::importPickUpAt($item->card_pick_up_arrangement, $db);
					$profile_obj->non_pick_up_at = $profile_obj->pick_up_at;
                    $profile_obj->mem_card_outlet = $profile_obj->pick_up_at;
                    $profile_obj->bation = null;
                    $profile_obj->other_hobbies  = null;
                    $profile_obj->o_o_clubs  = null;
                    $profile_obj->project_id  = 1;
                    $profile_obj->club_id  = null;
                    $profile_obj->alternative_email  = null;
                    $profile_obj->o_education = null ;
                    $profile_obj->o_bation  = null;
                    $profile_obj->o_source  = WrdHelper::importSource($item->application_received_from, $db);
                    $profile_obj->own_car = null ;
                    $profile_obj->num_children = null ;
                    $profile_obj->weekend_action = null ;
                    $profile_obj->modify_by  = null;
                    $profile_obj->delivery_date = $item->delivered_vipcard_date;
                    $profile_obj->renew = 'A' ;
                    /*********** Date ***********/
					if($item->delivered_vipcard_date != ''){
                        $profile_obj->non_pick_up_date = $item->delivered_vipcard_date;
                    } 
                    else{
                        $profile_obj->non_pick_up_date = '';
                    }
					
                    if($item->receiving_slip != ''){
                        $profile_obj->pick_up_date = $item->receiving_slip;
                    } 
                    else{
                        $profile_obj->pick_up_date = '';
                    }    
                    
                    $profile_obj->swipe_card = $item->swipe_card;
                    $profile_obj->lprefer = (($profile_obj->nationality == 249 || $profile_obj->nationality == 0) ? 1 : 2);
                    
                    if($item->status == 1)
                    	$db->insertObject('#__wrd_profile', $profile_obj);
                    elseif($item->status == 0){
                    	//find vipnumber
                    	$id_query = 'SELECT p.id,p.user_id
									FROM #__wrd_profile as p
									LEFT JOIN #__users as u ON p.user_id = u.id
									WHERE p.member_id = '.$profile_obj->member_id.' 
									AND u.block = 0';
                    			
                    	$db->setQuery($id_query);
                    	$cid = $db->loadObject()->id;
                    	
                    	unset($profile_obj->user_id);
                    	
                    	$profile_obj->id = $cid;
                    	$db->updateObject('#__wrd_profile', $profile_obj,'id');
                    }    

                echo 'Insert user id '.$insert_id.', '.$profile_obj->dob.'__'.$obj->name.'<br />';
                /*** Update Master List ***/
                
                $query = "
                    UPDATE #__masterlist
                    SET `status` = 2 
                    WHERE id = 
                ".$item->id;

				$db->setQuery($query);
                $db->query();
                
                //update pass
                $arrdob = explode('-', $profile_obj->dob);
                $newpass =  md5($profile_obj->member_id.$arrdob[0]);
                
                $subquery = 'UPDATE #__users SET password = "'.$newpass.'" WHERE id = '.$insert_id;
                $db->setQuery($subquery)->query();
		}
	}
    
	public function removefile(){
		$id = JRequest::getVar('id');

		if($id == 0)
			return false;
		
		$path = JPATH_SITE.DS.'wrd';
		$db = JFactory::getDBO();
		$query = 'SELECT * FROM #__wrd_file WHERE id = '.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();

		//delete file
		$dest 	= $path.DS.$rs->type.DS.$rs->name;
		$dest1 	= $path.DS.'thumb'.DS.$rs->name;

		JFile::delete($dest);
		JFile::delete($dest1);

		//delete id
		$query = 'DELETE FROM #__wrd_file WHERE id = '.$id;
		$db->setQuery($query);
		$db->query();

		jexit();
		return true;
	}

	
	public function import(){
		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', 86400);
		$mainframe = JFactory::getApplication();
		$user = JFactory::getUser();
		$db = JFactory::getDbo();

		$id = JRequest::getVar('id');
		$limit = 50;
		
		$filename = JRequest::getVar('filename');
		$fileid = $mainframe->getUserState('fileid',0);
		if($fileid == 0)
			$result['err'] = 'session expire';
        
		require_once JPATH_COMPONENT_ADMINISTRATOR.DS.'classes'.DS.'csv.php';
		$csv = new File_CSV_DataSource();
		
		$file = $csv->load(JPATH_ROOT.DS.'wrd'.DS.'transaction'.DS.$filename);
		if (!$csv->isSymmetric())
			$result['err'] = 'file has headers and rows with different lengths cannot connect';
		
		$header = $csv->getHeaders();
		$arr = array();

		foreach($header as $val=>$row ){
		
			if($row == ('Member ID'))
				$arr['vip_number'] = $val;
			
			if($row == ('Check#'))
				$arr['transaction_id'] = $val;
			
			if($row == ('Cover'))
				$arr['pax'] = $val;
			
			if($row == ('BusinessDate'))
				$arr['date_receipt'] = $val;
				
			if($row == ('BeginTime'))
				$arr['time_receipt'] = $val;
				
			if($row == ('EndTime'))
				$arr['endtime'] = $val;
			
			if($row == ('Outlet Code'))
				$arr['outlet'] = $val;
			
			if($row == ('StoreCode'))
				$arr['store'] = $val;
			
			if($row == ('Food'))
				$arr['food'] = $val;
			
			if($row == ('Beverage'))
				$arr['beverage'] = $val;
			
			if($row == ('Liquor'))
				$arr['liquor'] = $val;
			
		    	if($row == ('Other'))
				$arr['other'] = $val;
			
			if($row == ('Discount'))
				$arr['discount'] = $val;
			
			if($row == ('Net Sale'))
				$arr['netsale'] = $val;
			
			if($row == ('Service Charge'))
				$arr['sc'] = $val;
			
			if($row == ('Actual Paid'))
				$arr['total'] = $val;
			
			if($row == ('Tax'))
				$arr['vat'] = $val;
		}
		
		$total = $csv->countRows();
		$obj = new stdClass();
		
		for($i = $id; $i< ($id + $limit); $i++){
			if($i >= $total){
				$query = 'update #__wrd_file SET product_id = -1 WHERE id='.$fileid;
				$db->setQuery($query);
				$db->query();
				break;
			}

			$row = ($csv->getRow($i));

			//caculate date & time
			$tmp = explode('/',$row[$arr['date_receipt']]);
			$date_receipt = $tmp[2].'-'.$tmp[1].'-'.$tmp[0];
			$endtime = $tmp[2].'-'.$tmp[1].'-'.$tmp[0];
			
			unset($tmp);
			$tmp = explode(' ',$row[$arr['time_receipt']]);
			$new_tmp = explode(':',$tmp[0]);
			
			if($tmp[1] == 'PM')
				if(intval($new_tmp[0]) < 12)
					$new_tmp[0] = intval($new_tmp[0]) + 12;
			
			$date_receipt = $date_receipt .' '.$new_tmp[0].':'.$new_tmp[1].':'.$new_tmp[2];
			
			unset($tmp);
			$tmp = explode(' ',$row[$arr['endtime']]);
			$new_tmp = explode(':',$tmp[0]);
			
			if($tmp[1] == 'PM')
				if(intval($new_tmp[0]) < 12)
					$new_tmp[0] = intval($new_tmp[0]) + 12;
				
			$endtime = $endtime .' '.$new_tmp[0].':'.$new_tmp[1].':'.$new_tmp[2];
			
			$vowels = array(",", ".");
			$obj->id = null;
			$obj->vip_number = substr($row[$arr['vip_number']],4,-2);
			
			$obj->transaction_id = $row[$arr['transaction_id']];
			$obj->date_receipt = $date_receipt;
			$obj->endtime = $endtime;
			$obj->outlet = $row[$arr['store']].$row[$arr['outlet']];
			
			$qr = 'SELECT outlet_date FROM #__wrd_profile WHERE member_id = "'.$obj->vip_number.'"';
			$db->setQuery($qr);	
			$outlet_date = $db->loadObject();
			if($outlet_date->outlet_date == NULL){
		
				$q = 'UPDATE `#__wrd_profile` SET `outlet_code` = "'.$obj->outlet.'",`outlet_date` = "'.$obj->date_receipt.'" WHERE `#__wrd_profile`.`member_id` ="'.$obj->vip_number.'"';
				$db->setQuery($q);
				$db->query();
			}
			else if(($outlet_date->outlet_date < $obj->date_receipt)){
				$q = 'UPDATE `#__wrd_profile` SET `outlet_code` = "'.$obj->outlet.'",`outlet_date` = "'.$obj->date_receipt.'" WHERE `#__wrd_profile`.`member_id` ="'.$obj->vip_number.'"';
				$db->setQuery($q);
				$db->query();
			}
			$obj->pax = $row[$arr['pax']];
			$obj->food = str_ireplace($vowels, '', $row[$arr['food']]);
			$obj->beverage = str_ireplace($vowels, '', $row[$arr['beverage']]);
			$obj->liquor = 0;
			$obj->other = str_ireplace($vowels, '', $row[$arr['other']]);
			$obj->discount = str_ireplace($vowels, '', $row[$arr['discount']]);
			$obj->netsale = intval(str_ireplace($vowels, '', $row[$arr['netsale']]));
			$obj->sc = str_ireplace($vowels, '', $row[$arr['sc']]);
			$obj->vat = str_ireplace($vowels, '', $row[$arr['vat']]);
			$obj->total = str_ireplace($vowels, '', $row[$arr['total']]);
			$obj->created_date = date("Y-m-d H:i:s");
			$obj->created_id = $user->id;
			$obj->pay_type = null;
			$obj->file_id = $fileid;
			$db->insertObject('#__wrd_transaction', $obj);
			
			$month = date('m',strtotime($date_receipt));
			$year = date('Y',strtotime($date_receipt));
			if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
				while(($month != date('m'))||($year != date('Y'))){
					WrdHelper::uSummarySpend($obj->vip_number,$year,$month);
					if($month+1 <=12) ++$month;
					else {$month = 1;++$year;}
				}
			}
			
			WrdHelper::uSummarySpend($obj->vip_number,date('Y'),date('m'));
			
			$totalSpend = WrdHelper::getTotalTransaction($obj->vip_number);
			$sql = 'UPDATE #__wrd_profile SET total_spend = '.$totalSpend->total .' WHERE member_id = '.$obj->vip_number;
			$db->setQuery($sql);
			$db->query();
			
		}
		
		$result['total'] = $total;
		$result['current'] = $id + $limit <= $total ? $id+$limit : $total;
	
		echo json_encode($result);
		jexit();
	}
	
	function convert3years(){
		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', 86400);
		$mainframe = JFactory::getApplication();

		$db = JFactory::getDbo();
		$created_id = '42';


		$query = "SELECT id,food,beverage,other,netsale,discount,date_receipt FROM #__wrd_transaction WHERE `convert` = 0 AND file_id = -1 LIMIT 0 ,10000";
		
		$db->setQuery($query);
		$data = $db->loadObjectList();
		
		if(count($data) > 0){
			$db = JFactory::getDbo();
				
			$moneyForOnePoint = PointProvider::getConfigByName($db, 'money_for_one_point');
			$moneyForOnePoint = ($moneyForOnePoint > 0 ? $moneyForOnePoint : 50000);
				
			$defaultPointPerMoney  = PointProvider::getConfigByName($db, 'default_point_per_money');
			$defaultPointPerMoney = ($defaultPointPerMoney > 0 ? $defaultPointPerMoney : 100);
		
			foreach($data as $val=>$item){
				//Call function machPoint in components/com_wrd/helpers/wrd.php.Note by Hung
				$point = WrdHelper::machPoint($item->id,'transaction');
					
				if($point->point == 0){
					$point->point = $defaultPointPerMoney;
				}
		
				if(($point->f==0)&&($point->b==0)&&($point->o==1))
					$p = intval(($item->other) / $moneyForOnePoint) * $point->point;
		
				else if(($point->f==0)&&($point->b==1)&&($point->o==0))
					$p = intval(($item->beverage) / $moneyForOnePoint) * $point->point;
		
				else if(($point->f==0)&&($point->b==1)&&($point->o==1))
					$p = intval(($item->beverage+$item->other) / $moneyForOnePoint) * $point->point;
		
				else if(($point->f==1)&&($point->b==0)&&($point->o==0))
					$p = intval($item->food / $moneyForOnePoint) * $point->point;
		
				else if(($point->f==1)&&($point->b==0)&&($point->o==1))
					$p = intval(($item->food+$item->other) / $moneyForOnePoint) * $point->point;
		
				else if(($point->f==1)&&($point->b==1)&&($point->o==0))
					$p = intval(($item->food+$item->beverage) / $moneyForOnePoint) * $point->point;
		
				else
					$p = intval(($item->netsale) / $moneyForOnePoint) * $point->point;
		
				$expire  = WrdHelper::calculateExpiredDate($item->date_receipt);
		
				if($expire != '0000-00-00'){
					if(strtotime($expire.' 23:59:59') < time())
						$expired = 1;
					else $expired = 0;
				}
				else
					$expired = 0;
		
				//insert point table
				$obj = new stdClass;
				$obj->id = null;
				$obj->user_id = $point->user_id;
				$obj->transaction = $point->tran;
				$obj->type = 'transaction';
				$obj->point = $p;
				$obj->expire = $expire;
				$obj->expired = $expired;
				$obj->remain = $p;
				$obj->des = 'transaction';
				$obj->created_id = $created_id ;
				$obj->created_date = $item->date_receipt;
				$obj->modify_id = '' ;
				$obj->modify_date = '' ;
				$db->insertObject('#__wrd_point', $obj);
		
				// Update lai point summary cho user
				$month = date('m',strtotime($obj->created_date));
				$year = date('Y',strtotime($obj->created_date));
		
				if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
						
					while(($month != date('m'))||($year != date('Y'))){
						WrdHelper::updateSummaryPoint($obj->user_id,$year,$month);
						if($month+1 <=12) ++$month;
						else {$month = 1;++$year;}
					}
				}
				WrdHelper::updateSummaryPoint($obj->user_id,date('Y'),date('m'));

				$p_o_u = WrdHelper::getPoints($obj->user_id);
				$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point.',point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$obj->user_id;
				$db->setQuery($sql);
				$db->query();
		
				$query = 'UPDATE #__wrd_transaction SET `convert` = 1 WHERE transaction_id ='.$point->tran;
		
				$db->setQuery($query);
				$db->query();
			}
				
			echo 'done';
		}
		else{
			echo 'empty';
		}
	
	}
	
	function convert(){
		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', 86400);
		$mainframe = JFactory::getApplication();
		$start = JRequest::getInt('start',0);
		$total = JRequest::getInt('total',0);
		$db = JFactory::getDbo();
		$user = JFactory::getUser();
		$created_id = empty($user->id) ? '' : $user->id ;
		$fileid = $mainframe->getUserState('fileid',0);
		
		$query = "SELECT id,food,beverage,other,netsale,discount,date_receipt FROM #__wrd_transaction WHERE `convert` = 0 AND file_id = {$fileid} LIMIT 0 ,20";
		
		$db->setQuery($query);
		$data = $db->loadObjectList();
		
		if($total == 0){
			$query = "SELECT count(id) as total FROM #__wrd_transaction WHERE `convert` = 0 AND file_id = {$fileid} ";
			$db->setQuery($query);
			$t = $db->loadObject();
			$total = $t->total ;
		}

		if(count($data) > 0){
			$db = JFactory::getDbo();
			
			$moneyForOnePoint = PointProvider::getConfigByName($db, 'money_for_one_point');			
			$moneyForOnePoint = ($moneyForOnePoint > 0 ? $moneyForOnePoint : 50000);
			
			$defaultPointPerMoney  = PointProvider::getConfigByName($db, 'default_point_per_money');
			$defaultPointPerMoney = ($defaultPointPerMoney > 0 ? $defaultPointPerMoney : 100);
		
			foreach($data as $val=>$item){
				$point = WrdHelper::machPoint($item->id,'transaction');
			
				if($point->point == 0){
					$point->point = $defaultPointPerMoney;
				}
				
				if(($point->f==0)&&($point->b==0)&&($point->o==1)) 
					$p = intval(($item->other) / $moneyForOnePoint) * $point->point;
				
				else if(($point->f==0)&&($point->b==1)&&($point->o==0)) 
					$p = intval(($item->beverage) / $moneyForOnePoint) * $point->point;
				
				else if(($point->f==0)&&($point->b==1)&&($point->o==1)) 
					$p = intval(($item->beverage+$item->other) / $moneyForOnePoint) * $point->point;
				
				else if(($point->f==1)&&($point->b==0)&&($point->o==0)) 
					$p = intval($item->food / $moneyForOnePoint) * $point->point;
				
				else if(($point->f==1)&&($point->b==0)&&($point->o==1)) 
					$p = intval(($item->food+$item->other) / $moneyForOnePoint) * $point->point;
				
				else if(($point->f==1)&&($point->b==1)&&($point->o==0)) 
					$p = intval(($item->food+$item->beverage) / $moneyForOnePoint) * $point->point;
				
				else 
					$p = intval(($item->netsale) / $moneyForOnePoint) * $point->point;
				
				$expire  = WrdHelper::calculateExpiredDate($item->date_receipt);
				
				if($expire != '0000-00-00'){
					if(strtotime($expire.' 23:59:59') < time()) 
						$expired = 1;
					else $expired = 0;
				}
				else
					$expired = 0;
				
 				//insert point table
				$obj = new stdClass;
				$obj->id = null;
	  			$obj->user_id = $point->user_id;
				$obj->transaction = $point->tran;
				$obj->type = 'transaction';
				$obj->point = $p;
				$obj->expire = $expire;
				$obj->expired = $expired;
				$obj->remain = $p;
				$obj->des = 'transaction';
				$obj->created_id = $created_id ;
				$obj->created_date = $item->date_receipt;
				$obj->modify_id = '' ;
				$obj->modify_date = '' ;
				$db->insertObject('#__wrd_point', $obj);
				
				// Update lai point summary cho user
				$month = date('m',strtotime($obj->created_date));
				$year = date('Y',strtotime($obj->created_date));
				
				if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
					
					while(($month != date('m'))||($year != date('Y'))){
						WrdHelper::updateSummaryPoint($obj->user_id,$year,$month);
						if($month+1 <=12) ++$month;
						else {$month = 1;++$year;}
					}
				}
				WrdHelper::updateSummaryPoint($obj->user_id,date('Y'),date('m'));
				
				$p_o_u = WrdHelper::getPoints($obj->user_id);
				$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point.',point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$obj->user_id;
				$db->setQuery($sql);
				$db->query();
				
				$query = 'UPDATE #__wrd_transaction SET `convert` = 1 WHERE transaction_id ='.$point->tran;
				
				$db->setQuery($query);
				$db->query();
			}
			
			$result['total'] = $total;
			$result['data'] = count($data);
			
			if($start + 20 <=  $total)
				$result['current'] = $start + 20;
			else
				$result['current'] = $total;
		}
		else{
			$query = 'update #__wrd_file SET product_id = -2 WHERE id='.$fileid;
			$db->setQuery($query);
			$db->query();
			
			$result['data'] = 0;
			$result['total'] = $total;
			
			if($start + 20 <=  $total)
				$result['current'] = $start + 20;
			else
				$result['current'] = $total;
		}
		echo json_encode($result);
		jexit();
	}
	
	function getCompanies(){
		
		$q = JRequest::getVar('q');
		$model = $this->getModel('companyname');

		$tagList = $model->getListCompany($q);
	
		if(is_array($tagList))
		{
			foreach($tagList as $t)
			{
				echo "{$t->name}\n";
			}
		}

		jexit();
	}
	
	//migration 
	public function mergeUser(){
		$db = JFactory::getDbo();
		
		$query = 'SELECT * FROM vip_users';
		$user_obj = $db->setQuery($query)->loadObjectList();

        foreach($user_obj as $user_item){
			
			$newuser_obj = new stdClass();
			$newuser_obj->id 				= 	$user_item->id;
			$newuser_obj->name				=	$user_item->name;
			$newuser_obj->username			=	$user_item->username;
			$newuser_obj->email				=	$user_item->email;
			$newuser_obj->password			=	$user_item->password;
			$newuser_obj->block				=	$user_item->block;
			$newuser_obj->sendEmail			=	$user_item->sendEmail;
			$newuser_obj->registerDate		= 	$user_item->registerDate;
			$newuser_obj->lastvisitDate		= 	$user_item->lastvisitDate;
			$newuser_obj->activation		= 	$user_item->activation;
			$newuser_obj->params			= 	$user_item->params;
			$newuser_obj->lastResetTime		=	$user_item->lastResetTime;
			$newuser_obj->resetCount		= 	$user_item->resetCount;
			$newuser_obj->otpKey			=	'';
			$newuser_obj->otep				= 	'';
			
			$check_query = 'SELECT * FROM #__users WHERE id = '.$newuser_obj->id;
			$db->setQuery($check_query);
			$check_rs = $db->loadObject();
			if(intval($check_rs->id) == 0){
				$db->insertObject('#__users', $newuser_obj);
				print_r($newuser_obj);
				echo '<hr>';
			}
			
        }
	}
	
	public function mergeUserGroup(){
		$db = JFactory::getDbo();
		
		$query = 'SELECT * FROM vip_user_usergroup_map';
		$user_group_obj = $db->setQuery($query)->loadObjectList();
		
		foreach($user_group_obj as $user_group_item){
			print_r($user_group_item);
			$newuser_group_obj = new stdClass();
			$newuser_group_obj->user_id 	= 	$user_group_item->user_id;
			$newuser_group_obj->group_id	=	$user_group_item->group_id;
			
				
			$db->insertObject('#__user_usergroup_map', $newuser_group_obj);
			echo '<hr>';
		}
	}
	
	public function migrationCategory(){
		$db = JFactory::getDbo();
		
		$query = 'SELECT * FROM vip_categories';
		$cat_obj = $db->setQuery($query)->loadObjectList();
		
		foreach ($cat_obj as $catobjitem){
			$new_catitem = new stdClass();
			
			$new_catitem->id 		= $catobjitem->id;
			$new_catitem->asset_id 	= $catobjitem->asset_id;
			$new_catitem->parent_id = $catobjitem->parent_id;
			$new_catitem->lft 		= $catobjitem->lft;
			$new_catitem->rgt 		= $catobjitem->rgt;
			$new_catitem->level 	= $catobjitem->level;
			$new_catitem->path 		= $catobjitem->path;
			$new_catitem->extension = $catobjitem->extension;
			$new_catitem->title 	= $catobjitem->title;
			$new_catitem->alias 	= $catobjitem->alias;
			$new_catitem->note 			= $catobjitem->note;
			$new_catitem->description = $catobjitem->description;
			$new_catitem->published = $catobjitem->published;
			$new_catitem->checked_out = $catobjitem->checked_out;
			$new_catitem->checked_out_time = $catobjitem->checked_out_time;
			$new_catitem->access = $catobjitem->access;
			$new_catitem->params = $catobjitem->params;
			$new_catitem->metadesc = $catobjitem->metadesc;
			$new_catitem->metakey = $catobjitem->metakey;
			$new_catitem->metadata = $catobjitem->metadata;
			$new_catitem->created_user_id = $catobjitem->created_user_id;
			$new_catitem->created_time = $catobjitem->created_time;
			$new_catitem->modified_user_id = $catobjitem->modified_user_id;
			$new_catitem->modified_time = $catobjitem->modified_time;
			$new_catitem->hits = $catobjitem->hits;
			$new_catitem->language = $catobjitem->language;
			$new_catitem->version = 0;

			$check_query = 'SELECT * FROM #__categories WHERE id = '.$new_catitem->id;
			$db->setQuery($check_query);
			$check_rs = $db->loadObject();
			if(intval($check_rs->id) == 0){
				$db->insertObject('#__categories', $new_catitem);
				print_r($new_catitem);
				echo '<hr>';
			}
		}
		
	}
	
	public function migrationContent(){
		$db = JFactory::getDbo();
		
		$query = 'SELECT * FROM vip_content';
		$content_obj = $db->setQuery($query)->loadObjectList();
		
		foreach($content_obj as $item_obj){
			$newcontentobj = new stdClass();
			$newcontentobj->id = $item_obj->id;
			$newcontentobj->asset_id = $item_obj->asset_id;
			$newcontentobj->title = $item_obj->title;
			$newcontentobj->alias = $item_obj->alias;
			
			$item_obj->title_alias;
			
			$newcontentobj->introtext = $item_obj->introtext;
			$newcontentobj->fulltext = $item_obj->fulltext;
			$newcontentobj->state = $item_obj->state;
			
			$item_obj->sectionid;
			$item_obj->mask;
			
			$newcontentobj->catid = $item_obj->catid;
			$newcontentobj->created = $item_obj->created;
			$newcontentobj->created_by = $item_obj->created_by;
			$newcontentobj->created_by_alias = $item_obj->created_by_alias;
			$newcontentobj->modified = $item_obj->modified;
			$newcontentobj->modified_by = $item_obj->modified_by;
			$newcontentobj->checked_out = $item_obj->checked_out;
			$newcontentobj->checked_out_time = $item_obj->checked_out_time;
			$newcontentobj->publish_up = $item_obj->publish_up;
			$newcontentobj->publish_down = $item_obj->publish_down;
			$newcontentobj->images = $item_obj->images;
			$newcontentobj->urls = $item_obj->urls;
			$newcontentobj->attribs = $item_obj->attribs;
			$newcontentobj->version = $item_obj->version;
			
			$item_obj->parentid;
			
			$newcontentobj->ordering = $item_obj->ordering;
			$newcontentobj->metakey = $item_obj->metakey;
			$newcontentobj->metadesc = $item_obj->metadesc;
			$newcontentobj->access = $item_obj->access;
			$newcontentobj->hits = $item_obj->hits;
			$newcontentobj->metadata = $item_obj->metadata;
			$newcontentobj->featured = $item_obj->featured;
			$newcontentobj->language = $item_obj->language;
			$newcontentobj->xreference = $item_obj->xreference;
			
			$check_query = 'SELECT * FROM #__content WHERE id = '.$newcontentobj->id;
			$db->setQuery($check_query);
			$check_rs = $db->loadObject();
			
			if(intval($check_rs->id) == 0){
				$db->insertObject('#__content', $newcontentobj);
				print_r($newcontentobj);
				echo '<hr>';
			}
		}
	}

	public function migrationContentFrontPage(){
		$db = JFactory::getDbo();
		
		$query = 'SELECT * FROM vip_content_frontpage';
		$contentfp_obj = $db->setQuery($query)->loadObjectList();
		
		foreach ($contentfp_obj as $fpitem){
			$newfpitem = new stdClass();
			
			$newfpitem->content_id = $fpitem->content_id;
			$newfpitem->ordering = $fpitem->ordering;

			
			$check_query = 'SELECT * FROM #__content_frontpage WHERE content_id = '.$newfpitem->content_id;
			$db->setQuery($check_query);
			$check_rs = $db->loadObject();
				
			if(intval($check_rs->content_id) == 0){
				$db->insertObject('#__content_frontpage', $newfpitem);
				print_r($newfpitem);
				echo '<hr>';
			}
		}
	}
	
	public function migrationMenuType(){
		$db = JFactory::getDbo();
		
		$query = 'SELECT * FROM vip_menu_types';
		$menutype_obj = $db->setQuery($query)->loadObjectList();
		
		foreach ($menutype_obj as $menutype_item){
			
			$menutype_item_new = new stdClass();
			
			$menutype_item_new->id = $menutype_item->id;
			$menutype_item_new->menutype = $menutype_item->menutype;
			$menutype_item_new->title = $menutype_item->title;
			$menutype_item_new->description = $menutype_item->description;
			
			$check_query = 'SELECT * FROM #__menu_types WHERE id = '.$menutype_item_new->id;
			$db->setQuery($check_query);
			$check_rs = $db->loadObject();
			
			if(intval($check_rs->id) == 0){
				$db->insertObject('#__menu_types', $menutype_item_new);
				print_r($menutype_item_new);
				echo '<hr>';
			}
		}
	}
	
	public function migrationMenu(){
		
		# dont install any component before run this 
		$db = JFactory::getDbo();
	
		$query = 'SELECT * FROM `vip_menu` where menutype != "main" AND menutype != "menu"';
		$menu_obj = $db->setQuery($query)->loadObjectList();
	
		foreach ($menu_obj as $menu_item){
				
			$menu_item_new = new stdClass();
			
			$menu_item_new->id = $menu_item->id;
			$menu_item_new->menutype = $menu_item->menutype;
			$menu_item_new->title = $menu_item->title;
			$menu_item_new->alias = $menu_item->alias;
			$menu_item_new->note = $menu_item->note;
			$menu_item_new->path = $menu_item->path;
			$menu_item_new->link = $menu_item->link;
			$menu_item_new->type = $menu_item->type;
			$menu_item_new->published = $menu_item->published;
			$menu_item_new->parent_id = $menu_item->parent_id;
			$menu_item_new->level = $menu_item->level;
			$menu_item_new->component_id = $menu_item->component_id;
			
			$menu_item->ordering;
			
			$menu_item_new->checked_out = $menu_item->checked_out;
			$menu_item_new->checked_out_time = $menu_item->checked_out_time;
			$menu_item_new->browserNav = $menu_item->browserNav;
			$menu_item_new->access = $menu_item->access;
			$menu_item_new->img = $menu_item->img;
			$menu_item_new->template_style_id = $menu_item->template_style_id;
			$menu_item_new->params = $menu_item->params;
			$menu_item_new->lft = $menu_item->lft;
			$menu_item_new->rgt = $menu_item->rgt;
			$menu_item_new->home = $menu_item->home;
			$menu_item_new->language = $menu_item->language;
			$menu_item_new->client_id = $menu_item->client_id;
				
			$check_query = 'SELECT * FROM #__menu WHERE id = '.$menu_item_new->id;
			$db->setQuery($check_query);
			$check_rs = $db->loadObject();
				
			if(intval($check_rs->id) == 0){
				$db->insertObject('#__menu', $menu_item_new);
				print_r($menu_item_new);
				echo '<hr>';
			}
			else{
				echo 'item already have';
				print_r($menu_item_new);
			}
		}
	}
	
	function migrationBanner(){
		$db = JFactory::getDbo();
		
		$query = 'SELECT * FROM `vip_banners`';
		$banner_obj = $db->setQuery($query)->loadObjectList();
		foreach ($banner_obj as $banner_obj_item){
			$bannernew_obj_item = new stdClass();
			
			$bannernew_obj_item->id = $banner_obj_item->id;
			$bannernew_obj_item->cid = $banner_obj_item->cid;
			$bannernew_obj_item->type = $banner_obj_item->type;
			$bannernew_obj_item->name = $banner_obj_item->name;
			$bannernew_obj_item->alias = $banner_obj_item->alias;
			$bannernew_obj_item->imptotal = $banner_obj_item->imptotal;
			$bannernew_obj_item->impmade = $banner_obj_item->impmade;
			$bannernew_obj_item->clicks = $banner_obj_item->clicks;
			$bannernew_obj_item->clickurl = $banner_obj_item->clickurl;
			$bannernew_obj_item->state = $banner_obj_item->state;
			$bannernew_obj_item->catid = $banner_obj_item->catid;
			$bannernew_obj_item->description = $banner_obj_item->description;
			$bannernew_obj_item->custombannercode = $banner_obj_item->custombannercode;
			$bannernew_obj_item->sticky = $banner_obj_item->sticky;
			$bannernew_obj_item->ordering = $banner_obj_item->ordering;
			$bannernew_obj_item->metakey = $banner_obj_item->metakey;
			$bannernew_obj_item->params = $banner_obj_item->params;
			$bannernew_obj_item->own_prefix = $banner_obj_item->own_prefix;
			$bannernew_obj_item->metakey_prefix = $banner_obj_item->metakey_prefix;
			$bannernew_obj_item->purchase_type = $banner_obj_item->purchase_type;
			$bannernew_obj_item->track_clicks = $banner_obj_item->track_clicks;
			$bannernew_obj_item->track_impressions = $banner_obj_item->track_impressions;
			$bannernew_obj_item->checked_out = $banner_obj_item->checked_out;
			$bannernew_obj_item->checked_out_time = $banner_obj_item->checked_out_time;
			$bannernew_obj_item->publish_up = $banner_obj_item->publish_up;
			$bannernew_obj_item->publish_down = $banner_obj_item->publish_down;
			$bannernew_obj_item->reset = $banner_obj_item->reset;
			$bannernew_obj_item->created = $banner_obj_item->created;
			$bannernew_obj_item->language = $banner_obj_item->language;
			$bannernew_obj_item->created_by = $banner_obj_item->created;
			$bannernew_obj_item->created_by_alias = '';
			$bannernew_obj_item->modified = '';
			$bannernew_obj_item->modified_by = '';
			$bannernew_obj_item->version = 0;
			
			$check_query = 'SELECT * FROM #__banners WHERE id = '.$bannernew_obj_item->id;
			$db->setQuery($check_query);
			$check_rs = $db->loadObject();
			
			if(intval($check_rs->id) == 0){
				$db->insertObject('#__banners', $bannernew_obj_item);
				print_r($bannernew_obj_item);
				echo '<hr>';
			}
			else{
				echo 'item already have';
				print_r($bannernew_obj_item);
			}
		}
	}
	
	public function migrationBannerTrack(){
		$db = JFactory::getDbo();
		
		$query = 'SELECT * FROM `vip_banner_tracks`';
		$bannertrack_obj = $db->setQuery($query)->loadObjectList();
		
		$check_query = 'TRUNCATE #__banner_tracks';
		$db->setQuery($check_query)->query();
		
		foreach ($bannertrack_obj as $bannertrack_item){
			
			$bannertracknew_item = new stdClass();
			
			$bannertracknew_item->track_date = $bannertrack_item->track_date;
			$bannertracknew_item->track_type = $bannertrack_item->track_type;
			$bannertracknew_item->banner_id = $bannertrack_item->banner_id;
			$bannertracknew_item->count = $bannertrack_item->count;

			$db->insertObject('#__banner_tracks', $bannertracknew_item);
			print_r($bannertracknew_item);
			echo '<hr>';
		
		}
		
	}
}
?>
